package com.xtiim.battery.discharge.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.math.BigDecimal;
import java.util.Random;

/**
 * Double data util
 */
public class DoubleUtil {

    private static final Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    /**
     *
     * handle double decimal, always keep 3 decimal
     * @param value
     * @return
     */
    public static String handleDoubleDecimal(Double value) {

        if (value == null) {
            return null;
        }

        String valueStr = value.toString();
        int pointIndex = valueStr.indexOf(".");
        String integer = valueStr.substring(0, pointIndex);
        String decimal = valueStr.substring(pointIndex + 1);

        StringBuilder builder = new StringBuilder(integer);
        builder.append(".");
        Random random = new Random();
        if (decimal.length() == 1) {
            builder.append(decimal);

            int twoDigitNumbers = random.nextInt(9) + 11; //[11, 19]
            builder.append(twoDigitNumbers);
            return builder.toString();

        } else if (decimal.length() == 2) {
            builder.append(decimal);

            int oneDigitNumbers = random.nextInt(9) + 1; //[1, 9]
            builder.append(oneDigitNumbers);
            return builder.toString();

        } else if (decimal.length() >= 3) {
            String noDigitNumbers = decimal.substring(0, 3);
            builder.append(noDigitNumbers);
            return builder.toString();
        }

        return null;
    }

    public static void main(String[] args) {
//        for (int i = 0; i < 20; i++) {
//            String test = handleDoubleDecimal(12.0123);
//            System.out.println(test);
//        }

        Double d = Double.valueOf(12.12);

        BigDecimal bigDecimal = new BigDecimal(d.toString()).setScale(3, BigDecimal.ROUND_DOWN);
        System.out.println(bigDecimal);
        System.out.println(gson.toJson(bigDecimal));


        System.out.println(d);
        String s = new BigDecimal(d.toString()).setScale(3, BigDecimal.ROUND_DOWN).toPlainString();
        System.out.println(s);
        System.out.println(gson.toJson(s));

        Double doubleValue = new BigDecimal(d.toString()).setScale(3, BigDecimal.ROUND_DOWN).doubleValue();
        System.out.println(doubleValue);
        System.out.println(gson.toJson(doubleValue));


    }
}
